package com.xce.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.xce.order.entity.Order;
import com.xce.order.properties.OrderProperties;
import com.xce.order.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * @ClassName OrderController
 * @Description TODO
 * @Author lld
 * @Date 2025/6/25 1:02
 * @Version 1.0
 */
@Slf4j
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProperties orderProperties;

    @GetMapping("/createOrder")
    public Order createOrder(@RequestParam("productId") Long productId, @RequestParam("userId") Long userId) {

        return orderService.createOrder(productId,userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "productId") Long productId,
                         @RequestParam(value = "userId",required = false) Long userId) {

        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }


    public Order seckillFallback(Long productId,Long userId, Throwable ex) {
        Order order = new Order();
        order.setId(productId);
        order.setTotalAmount(BigDecimal.valueOf(0));
        order.setUserId(userId);
        log.error("seckillFallback...........");
        order.setNickName("异常"+ex.getClass());
        return order;
    }

    @RequestMapping("/config")
    public String config() {
        return "order.timeout："+orderProperties.getTimeout()+
                "; \norder.auto-confirm："+orderProperties.getAutoConfirm()+"; \ndb-url: "+orderProperties.getDbUrl();
    }


    @GetMapping("/readDb")
    public String readDb(HttpServletRequest request) {
    // public String readDb(@RequestHeader(value = "request", required = false) String request) {


        log.info("read success .....HttpServletRequest"+request.getHeader("request"));
        return "read db .....";
    }

    @GetMapping("/writeDb")
    public String writeDb() {
        return "write db .....";
    }
}
